const fs = require('fs')
const path = require('path')
const { logError, getSoleStr } = require('../func/util')
const { getToken, getAccount, setToken, getRole } = require('../mapping/access')

function canAccess(req, res) {
    try {
        const token = req.headers.usertoken
        const tokens = Object.values(getToken())

        if (tokens.includes(token)) {
            res.status(200)
            res.send('OK')
        } else {
            res.status(401)
            res.send('未获取授权')
        }
    } catch (e) {
        logError(e)
        res.status(500)
        res.send({ msg: '服务器未知错误' })
    }
}

function checkLogin(req, res) {
    try {
        const accounts = getAccount()
        const username = req.body.username
        const password = req.body.password
        const ok = accounts.some(
            account =>
                account.username === username && account.password === password
        )
        if (ok) {
            const token = getSoleStr()
            setToken(username, token)
            res.status(200)
            res.send({ msg: 'success', token })
        } else {
            res.status(200)
            res.send({ msg: 'fail: 账号/密码错误' })
        }
    } catch (e) {
        logError(e)
        res.status(500)
        res.send({ msg: '服务器未知错误' })
    }
}

function sendRole(req, res) {
    const roles = getRole()
    const accounts = getAccount()
    const token = req.params.token
    const tokens = getToken()
    for (const username in tokens) {
        if (tokens[username] === token) {
            // 找到对应账号的role
            for (const item of accounts) {
                if (item.username === username) {
                    res.status(200)
                    res.send({ msg: 'success', data: roles[item.role] })
                }
            }
        }
    }
}
module.exports = {
    canAccess,
    checkLogin,
    sendRole
}
